import { login, getInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import {
  getToken,
  setToken,
  removeToken,
  setTimeStamp
} from '@/utils/auth'
// 状态
const state = {
  token: getToken(),
  userInfo: {}
}
// 执行异步
const actions = {
  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result)
    setTimeStamp()
  },
  async getInfo(context) {
    const result = await getInfo()
    const avatar = await getUserDetailById(result.userId)
    const newResult = { ...result, ...avatar }
    context.commit('setUserInfo', newResult)
    return newResult
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
  }
}
// 修改状态
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = { ...userInfo }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}
